package teleradiologia.repository;

import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.Session;
import org.hibernate.Transaction;
import teleradiologia.domain.Diagnosticlab;
import teleradiologia.domain.Ordertype;
import teleradiologia.utils.HibernateUtil;
import teleradiologia.web.TechnicianController;

public class DiagnosticlabDaoImpl implements DiagnosticlabDao {
	private static final Log log = LogFactory
	.getLog(TechnicianController.class);
	
	@Override
	public String create(Diagnosticlab diagnosticlab) {

		Session session = HibernateUtil.getSessionFactory().openSession();
		Transaction tx = session.beginTransaction();

		String krsnumber = (String) session.save(diagnosticlab);

		tx.commit();
		session.close();

		return krsnumber;
	}

	@Override
	public void delete(Diagnosticlab diagnosticlab) {

		Session session = HibernateUtil.getSessionFactory().openSession();
		Transaction tx = session.beginTransaction();

		session.delete(diagnosticlab);

		tx.commit();
		session.close();

	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Diagnosticlab> getAll() {

		Session session = HibernateUtil.getSessionFactory().openSession();
		Transaction tx = session.beginTransaction();

		List<Diagnosticlab> diagnosticlabs = session
				.createQuery(
						"from Diagnosticlab diagnosticlab order by diagnosticlab.name asc")
				.list();

		tx.commit();
		session.close();
		return diagnosticlabs;
	}

	@Override
	public Diagnosticlab getByKrsnumber(String krsnumber) {

		Session session = HibernateUtil.getSessionFactory().openSession();
		Transaction tx = session.beginTransaction();

		Diagnosticlab diagnosticlab = (Diagnosticlab) session.get(
				Diagnosticlab.class, krsnumber);

		tx.commit();
		session.close();

		return diagnosticlab;
	}

	@Override
	public void update(Diagnosticlab diagnosticlab) {

		Session session = HibernateUtil.getSessionFactory().openSession();
		Transaction tx = session.beginTransaction();

		session.update(diagnosticlab);

		tx.commit();
		session.close();
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Object[]> getAllByOrdertype(Ordertype ordertype) {
		Session session = HibernateUtil.getSessionFactory().openSession();
		Transaction tx = session.beginTransaction();

		String query = "select diagnosticlab.krsnumber, offer.id "
				+ " from Ordertype as ordertype "
				+ " join ordertype.offers as offer "
				+ " join offer.diagnosticlab as diagnosticlab "
				+ " where :ordertype = ordertype ";

		List<Object[]> result = session.createQuery(query).setEntity(
				"ordertype", ordertype).list();

			
		tx.commit();
		session.close();
		
		return result;
	}
}
